#!/usr/bin/python
# coding:utf-8
"""
封装数据生成相关关键字
"""
__author__ = 'Martin Wang <357951@qq.com>'

import uuid
import string
import random
import time
import datetime
import base64
import pyzbar
import json
from robot.api import logger


def rand_uuid():

    """随机产生一个32位的uuid
    - :return: 返回uuid
    """
    temp = str(uuid.uuid1())
    return temp.replace("-", "")


def rand_name(prefix=None, length=5):
    """产生随机名字

    - :param prefix: 【选填】名字的前缀，可选值，类型：string
    - :param length: 【选填】名字的后缀的长度,类型：int
    - :return: 返回随机名字
    """
    rand_str = "".join(random.sample(string.digits, int(length)))
    str1_temp = rand_str if not prefix else prefix + rand_str
    return str1_temp


def rand_str(length):
    """随机产生指定长度的字符串

    - :param length: 【必填】字符串长度，类型：int
    - :return: 返回字符串
    """

    char = string.ascii_letters + string.digits + string.punctuation
    rand_str1 = "".join(random.choice(char) for x in range(int(length)))
    return rand_str1


def get_time_stamp():
    """获取时间戳

    - :return:返回时间戳
    """
    temp_time = str(int(time.time()*1000))
    return temp_time


def get_time_stamp_formatted(formatter="%Y-%m-%d %H:%M:%S"):
    """获取g格式化后的时间戳

    - :return:返回格式化后的时间戳
    """
    temp_time = time.strftime(formatter, time.localtime(time.time()))
    return temp_time


def time_delta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0):
    """在当前时间基础上进行时间增减操作

    - :param days:  【可选】单位：天；类型：整数
    - :param seconds: 【可选】单位：秒；类型：整数
    - :param microseconds: 【可选】单位：毫秒；类型：整数
    - :param milliseconds: 【可选】单位：千毫秒；类型：整数
    - :param minutes:【可选】单位：分钟；类型：整数
    - :param hours:【可选】单位：小时；类型：整数
    - :param weeks:【可选】单位：周；类型：整数
    - :return: 返回格式化后的时间

    - 举例：
    | Time Delta | days=5 |
    """
    # 获取当前时间
    now = datetime.datetime.now()
    # 当前时间加上半小时
    add_time = now + datetime.timedelta(days=days, seconds=seconds, microseconds=microseconds, milliseconds=milliseconds,
                                        minutes=minutes, hours=hours, weeks=weeks)
    # 格式化字符串输出
    formatted_time = add_time.strftime('%Y-%m-%d %H:%M:%S')
    return formatted_time


def random_chn(length):
    """随机生成中文字符串

    - :param length: 【必填】指定中文字符串的长度
    - :return: 返回生成的字符串
    """
    result = ""
    for i in range(int(length)):
        head = random.randint(0xb0, 0xf7)
        body = random.randint(0xa1, 0xf9)  # 在head区号为55的那一块最后5个汉字是乱码,为了方便缩减下范围
        val = f'{head:x}{body:x}'
        str = bytes.fromhex(val).decode('gb2312')
        result += str
    return result


def random_eng(length):
    """随机生成英文字符串

    - :param length: 【必填】指定英文字符串的长度
    - :return: 返回生成的字符串
    """
    result = ""
    for i in range(int(length)):
        s = chr(random.randint(65, 90))
        result += s
    return result
    

def random6():
    """随机生成英文字符串

    - :param length: 【必填】指定英文字符串的长度
    - :return: 返回生成的字符串
    """
    result = ""
    for i in range(int(6)):
        s = chr(random.randint(65, 90))
        result += s
    return result


def randomEmail():
    """随机生成英文字符串

    - :param length: 【必填】指定英文字符串的长度
    - :return: 返回生成的字符串
    """
    result = ""
    for i in range(int(6)):
        s = chr(random.randint(65, 90))
        result += s
    result = result+'@'+ result+'.com'
    return result


def base64_to_image(content64, path):
    """将base64编码转换成图片

    :param content64: base64编码
    :param path: 生产的图片路径，例如：qrcode.jpg
    :return:image_data：编码后的图片二进制流
    """
    image_data = base64.b64decode(content64)
    with open(path, 'wb') as f:
        f.write(image_data)
    f.close()
    return image_data


def image_to_base64(image_data):
    """将图片二进制流进行base64编码

    :param image_data: 图片二进制流
    :return:
    """
    base64_data = base64.b64encode(image_data)
    return base64_data


def write_file(path, content, mode='w'):
    with open(path, mode) as f:
        f.write(content)


def read_file(path, mode='r'):
    with open(path, mode) as f:
        content = f.readlines()
    return content


def compare_search_result(json_data, key, value, contain=0):
    """对比搜索结果中对应字段的值

    - :param contain: 是否为模糊查询
    - :param json_data: json结果
    - :param key: 要对比的参数
    - :param value: 对比的目标值
    - :param contain: 是否模糊对比，1是模糊，0是精确
    - :return: 返回1对比成功，对比一致。返回0对比失败，不一致
    """
    try:
        flag = 1
        logger.info("开始对比，获取到的数据 :{}".format(json_data))
        if json_data:
            for i in json_data:
                for k, v in i.items():
                    v = str(v)
                    if k == key and contain == 0:
                        if v != value:
                            logger.info("完全匹配对比，此数据不一致 :{}".format(i))
                            flag = 0
                    elif k == key and contain == 1:
                        if not v.__contains__(value):
                            logger.info("模糊匹配对比，此数据不包含值 :{}".format(i))
                            flag = 0
            return flag
        else:
            logger.info("data is empty")
            flag = 0
            return flag
    except Exception as e:
        raise Exception("Compare failed: {}".format(e))


def read_dic_key(json_data):
    """获取字典中的key 判断key是否存在

    - :param json_data: json结果
    - :return: 返回list
    """
    data_list =[]
    for key in json_data:
        data_list.append(key)
    return data_list


if __name__ == "__main__":
    a = time_delta(days=-5)
    print(a)



